﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpMUD.Framework.ComponentModel;
using System.Threading.Tasks;

namespace SharpMUD.Framework.Services.Threading
{
    public class TaskFactoryProviderService
        : ITaskFactoryProviderService
    {
        private readonly Dictionary<Tuple<TaskCreationOptions, TaskContinuationOptions>, TaskFactory> _TaskFactories = new Dictionary<Tuple<TaskCreationOptions, TaskContinuationOptions>, TaskFactory>(System.Collections.TypedStructuralComparisons<Tuple<TaskCreationOptions,TaskContinuationOptions>>.StructuralEqualityComparer);

        #region IService Members

        public IServicesHost ServicesHost
        {
            get; private set;
        }

        public void Initialize(IServicesHost servicesHost)
        {
            this.ServicesHost = servicesHost;



            this.IsInitialized = true;
        }

        public bool IsInitialized
        {
            get; private set;
        }

        #endregion

        #region ITaskFactoryProviderService Members

        public TaskFactory GetTaskFactory()
        {
            return GetTaskFactory(TaskCreationOptions.None, TaskContinuationOptions.None);
        }

        public TaskFactory GetTaskFactory(TaskContinuationOptions taskContinuationOptions)
        {
            return GetTaskFactory(TaskCreationOptions.None, taskContinuationOptions);
        }

        public TaskFactory GetTaskFactory(TaskCreationOptions taskCreationOptions)
        {
            return GetTaskFactory(taskCreationOptions, TaskContinuationOptions.None);
        }

        public TaskFactory GetTaskFactory(TaskCreationOptions taskCreationOptions, TaskContinuationOptions taskContinuationOptions)
        {
            var key = new Tuple<TaskCreationOptions,TaskContinuationOptions>(taskCreationOptions,taskContinuationOptions);
            lock (_TaskFactories)
            {

                if (!_TaskFactories.ContainsKey(key))
                {
                    _TaskFactories.Add(key, new TaskFactory(taskCreationOptions,taskContinuationOptions));
                }
                return _TaskFactories[key];
            }
        }

        #endregion
    }
}
